package com.pokermadness.servlets;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;

import com.pokermadness.game.Game;

@WebServlet("/GameServlet")
public class GameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public void init() {
		ServletContext context = getServletContext();
		context.setAttribute("active-sessions",
				new HashMap<String, HttpSession>());
	}
	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session;
		@SuppressWarnings("unchecked")
		HashMap<String, HttpSession> map = (HashMap<String, HttpSession>) getServletContext().getAttribute(
		"active-sessions");
		String key = getCookieValue(
				request.getCookies(), "session", "-1");
		if (map.containsKey(key)) {
			session = map.get(key);
		} else {
			session = request.getSession(true);
			map.put(session.getId(), session);
			session.setMaxInactiveInterval(600);
		}
		Game game = (Game) session.getAttribute("game");
		if (game == null) {
			game = new Game();
			game.startGame();
			session.setAttribute("game", game);
		}
		Cookie cookie = new Cookie("session", session.getId());
		cookie.setMaxAge(600);
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);
		response.setContentType("application/json");
		if (request.getParameterMap().containsKey("initGame")) {
			postGetInitGame(request, response, game);
		} else if (request.getParameterMap().containsKey("move")) {
			processPlayerMove(request, response, game);
		} else if (request.getParameterMap().containsKey("send")) {
			sendMove(request, response, game);
		} else if (request.getParameterMap().containsKey("finish")) {
			finishGame(request, response, game);
		} else if(request.getParameterMap().containsKey("end")) {
			endGame(session);
		} else if(request.getParameterMap().containsKey("isRunning")) {
			isRunning(request, response, game);
		}  else if(request.getParameterMap().containsKey("initSession")) {
			response.getWriter().write("");
		}
	}
	
	private void postGetInitGame(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		boolean addLog;
		if(request.getParameter("sendLog").equals("true"))
			addLog = true;
		else
			addLog = false;
		response.getWriter().write(game.getInitString(addLog));
	}
	
	private void isRunning(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		response.getWriter().write(game.getIsRunningString());
	}
	
	private void processPlayerMove(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		int move = Integer.parseInt(request.getParameter("move"));
		response.getWriter().write(game.makeMove(move));
	}
	
	private void sendMove(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		try {
			response.getWriter().write(game.playRound().toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	private void finishGame(HttpServletRequest request,
			HttpServletResponse response, Game game) throws IOException {
		response.getWriter().write(game.finishGame());
	}
	
	private void endGame(HttpSession session) {
		session.removeAttribute("game");
	}
	
	private String getCookieValue(Cookie[] cookies, String cookieName,
			String defaultValue) {
		if(cookies == null)
			return defaultValue;
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
				return (cookie.getValue());
		}
		return (defaultValue);
	}

}
